package com.hoshiicloud.withdraw.controller.gongmao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.withdraw.entity.UserInfo;
import com.hoshiicloud.withdraw.entity.WithdrawApplyRecord;
import com.hoshiicloud.withdraw.entity.WithdrawApplyResult;
import com.hoshiicloud.withdraw.param.ElectronicContractCallbackParam;
import com.hoshiicloud.withdraw.param.WithdrawalCallbackParam;
import com.hoshiicloud.withdraw.param.WithdrawalParam;
import com.hoshiicloud.withdraw.service.UserInfoService;
import com.hoshiicloud.withdraw.service.WithdrawApplyRecordService;
import com.hoshiicloud.withdraw.service.WithdrawApplyResultService;
import com.hoshiicloud.withdraw.util.gongmao.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 工猫提现对接的controller
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/gongmao")
@Api(value = "工猫提现", tags = {"工猫提现"})
public class GoongMaoController {

	/**
	 * 服务对象
	 */
	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 服务对象
	 */
	@Autowired
	private WithdrawApplyRecordService withdrawApplyRecordService;

	/**
	 * 服务对象
	 */
	@Autowired
	private WithdrawApplyResultService withdrawApplyResultService;

	@Value("${gongmao.requestUrl}")
	private String requestUrl;


	@Value("${apiPigUrl}")
	private String apiPigUrl;


	@ApiOperation(value = "提现结果回调地址")
	@PostMapping("/withdrawal/withdrawalCallback")
	public Response withdrawalCallback(@Valid WithdrawalCallbackParam param) {

		log.info("提现结果回调地址" + JSONUtil.toJsonStr(param));

		QueryWrapper<WithdrawApplyRecord> applyRecordQueryWrapper = new QueryWrapper<>();
		applyRecordQueryWrapper.lambda().eq(WithdrawApplyRecord::getRequestId, param.getRequestId());

		WithdrawApplyRecord withdrawApplyRecord = withdrawApplyRecordService.getOne(applyRecordQueryWrapper);

		Map<String, Object> paramApplyMap = new HashMap<>();
		paramApplyMap.put("status", "1".equals(param.getStatus()) ? 4 : 5);
		paramApplyMap.put("remark", param.getRemark());

		// 接收提现记录结果
		if (withdrawApplyRecord != null) {
			withdrawApplyRecord.setCurrentTax(param.getCurrentTax())
					.setCurrentManageFee(param.getCurrentManageFee())
					.setCurrentRealWage(param.getCurrentRealWage())
					.setBankName(param.getBankName())
					.setPayTime(param.getPayTime())
					.setRemark(param.getRemark());
			paramApplyMap.put("id", withdrawApplyRecord.getWithdrawRecordId());
			withdrawApplyRecordService.updateById(withdrawApplyRecord);
		}

		QueryWrapper<WithdrawApplyResult> withdrawApplyResult = new QueryWrapper<>();
		withdrawApplyResult.lambda().eq(WithdrawApplyResult::getRequestId, param.getRequestId());

		WithdrawApplyResult applyRecordServiceOne = withdrawApplyResultService.getOne(withdrawApplyResult);

		// 接收提现结果
		if (applyRecordServiceOne != null) {
			applyRecordServiceOne.setResult(param.getStatus());
			withdrawApplyResultService.updateById(applyRecordServiceOne);
		}
		String result = HttpUtil.post(apiPigUrl + "/audit/withdrawAudit/open/withdrawAudit", JSONUtil.toJsonStr(paramApplyMap));
		log.info("数据写回,对应的requestId为: " + param.getRequestId() + result);
		return Response.data(true);
	}


	@ApiOperation(value = "提现转账确认回调")
	@PostMapping("/withdrawal/confirmWithdrawalCallback")
	public Map<String, Object> confirmWithdrawalCallback(@Valid WithdrawalParam param) {

		log.info("提现转账确认回调" + JSONUtil.toJsonStr(param));
		QueryWrapper<WithdrawApplyRecord> applyRecordQueryWrapper = new QueryWrapper<>();

		applyRecordQueryWrapper.lambda().eq(WithdrawApplyRecord::getRequestId, param.getRequestId())
				.eq(WithdrawApplyRecord::getBankAccount, param.getBankAccount());

		WithdrawApplyRecord withdrawApplyRecord = withdrawApplyRecordService.getOne(applyRecordQueryWrapper);

		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("requestId", param.getRequestId());


		if (withdrawApplyRecord == null) {
			paramMap.put("status", 2);
			log.error("提现转账确认回调,但是根据请求方的requestId以及bankAccount获取记录失败" + JSONUtil.toJsonStr(param));
		} else {
			paramMap.put("status", 1);
		}

		return paramMap;
	}


	@ApiOperation(value = "电子合同回调地址")
	@PostMapping("/electronicContract/electronicContractCallback")
	public Response electronicContractCallback(@Valid ElectronicContractCallbackParam param) {

		log.info("电子合同回调地址" + JSONUtil.toJsonStr(param));

		userInfoService.electronicContractInfo(param);
		return Response.data(true);
	}

	@ApiOperation(value = "用户申请提现")
	@PostMapping("/withdrawal/withdrawalApply")
	public Response withdrawalApply(@RequestBody @Valid WithdrawalParam param) {

		// 存提现记录
		QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
		userInfoQueryWrapper.lambda().eq(UserInfo::getName, param.getName())
				.eq(UserInfo::getIsDel, 0)
				.eq(UserInfo::getIdcard, param.getIdentity())
				.eq(UserInfo::getBankAccount, param.getBankAccount());
		UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);

		if (userInfo == null) {
			return Response.data("该用户签约信息不一致或者未进行签约");
		}

		Map<String, Object> map = new HashMap<>();
		map.put("user_id", userInfo.getId());
		map.put("withdraw_record_id", param.getWithdrawRecordId());
		map.put("withdraw_platform_id", param.getWithdraPlatformId());

		int count = withdrawApplyResultService.getResult(map);

		if (count == 0) {
			WithdrawApplyRecord build = WithdrawApplyRecord.builder().amount(param.getAmount()).bankAccount(param.getBankAccount()).bankName(userInfo.getBankName())
					.userId(userInfo.getId()).dateTime(param.getDateTime()).createTime(new Date()).requestId(param.getRequestId())
					.updateTime(new Date()).withdrawPlatformId(param.getWithdraPlatformId()).withdrawRecordId(param.getWithdrawRecordId()).build();
			build.insert();
			// 项目第三方发起提现
			Map<String, Object> objectMap = BeanUtil.beanToMap(param);
			objectMap.remove("mobile");
			objectMap.put("appKey", SignUtil.APPKEY);
			objectMap.put("nonce", UUID.randomUUID().toString().replaceAll("-", ""));
			objectMap.put("timestamp", new Date().getTime());
			objectMap.put("sign", SignUtil.getSign(objectMap, SignUtil.APPSECRET));

			String res = HttpUtil.post(requestUrl + "/api/withdraw/doWithdraw", objectMap);
			log.info(res);
			JSONObject jsonObject = JSONUtil.parseObj(res);
			if (jsonObject.getBool("success")) {
				if (jsonObject.getJSONObject("data").getInt("opFlag") == 1) {
					WithdrawApplyResult.builder().createTime(new Date()).recordId(build.getId())
							.requestId(param.getRequestId()).updateTime(new Date()).result("4").build().insert();
					return Response.data("第三方处理中......");
				}
			}
			return Response.data(jsonObject.getStr("errorMsg"));
		}
		return Response.data("已经处理过");
	}

	@ApiOperation(value = "查询企业当前余额")
	@PostMapping("/withdrawal/getCompanyBalance")
	public Response getCompanyBalance() {
		Map<String, Object> objectMap = new HashMap<>();
		objectMap.put("appKey", SignUtil.APPKEY);
		objectMap.put("nonce", UUID.randomUUID().toString().replaceAll("-", ""));
		objectMap.put("timestamp", new Date().getTime());
		objectMap.put("sign", SignUtil.getSign(objectMap, SignUtil.APPSECRET));

		String res = HttpUtil.post(requestUrl + "/api/company/getBalance", objectMap);
		log.info(res);
		JSONObject jsonObject = JSONUtil.parseObj(res);
		if (jsonObject.getBool("success")) {
			return Response.data(jsonObject.getStr("data"));
		}
		return Response.failed(jsonObject.getStr("errorMsg"));
	}
}
